package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.Role;
import cn.wolfcode.wms.mapper.RoleMapper;
import cn.wolfcode.wms.page.PageResult;
import cn.wolfcode.wms.qo.QueryObject;
import cn.wolfcode.wms.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    public List<Role> listAll() {
        return roleMapper.selectAll();
    }

    public Role getById(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    public void saveOrUpdate(Role role, Long[] ids, Long[] menuIds) {
        if (role.getId() != null) {
            // 更新之前，先删除原有的关系
            roleMapper.deleteRelation(role.getId());
            roleMapper.deleteMenuRelation(role.getId());
            roleMapper.updateByPrimaryKey(role);
        } else {
            roleMapper.insert(role);
        }
        // 维护角色与权限之间的关系
        for (Long pId : ids) {
            roleMapper.insertRelation(role.getId(), pId);
        }
        for (Long menuId : menuIds) {
            roleMapper.insertMenuRelation(role.getId(), menuId);
        }
    }

    public void delete(Long id) {
        // 维护关系
        roleMapper.deleteRelation(id);
        roleMapper.deleteMenuRelation(id);
        roleMapper.deleteByPrimaryKey(id);
    }

    public PageResult query(QueryObject qo) {
        int rows = roleMapper.queryForCount(qo);
        if(rows==0){
            return PageResult.empty(qo.getPageSize());
        }
        List<?> result= roleMapper.queryForList(qo);
        return new PageResult(rows, result,qo.getCurrentPage(),qo.getPageSize());
    }
}
